package lagou.resultmapper;


import com.google.gson.Gson;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自定义结果映射，主要用来处理高亮
 */
public class ESSearchResultMapper implements SearchResultMapper {


    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
        System.out.println(1);
        //获得总记录数
        long totalHits = searchResponse.getHits().getTotalHits();
        //记录列表，用来保存返回的结果
        List<T> list = new ArrayList<>();

        // 获取搜索结果(真正的的记录)
        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            if (hits.getHits().length <= 0) {
                return null;
            }

            String json = hit.getSourceAsString();
            Map<String, Object> map = hit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            for (Map.Entry<String, HighlightField> highlightField : highlightFields.entrySet()) {
                // 获取高亮的Key
                String key = highlightField.getKey();
                // 获取高亮的Value，这就是我们操作添加的高亮信息
                HighlightField value = highlightField.getValue();
                Text[] fragments = value.getFragments();
                map.put(key, fragments[0].toString());
            }
            Gson gson = new Gson();

            T item = gson.fromJson(gson.toJson(map), aClass);
            list.add(item);
        }

        return new AggregatedPageImpl<>(list, pageable, totalHits);
    }
}





